package com.boss.soft.lb;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ljx
 * @date 2020/8/6 16:30
 */
@Slf4j
@Component
public class MyLb implements MyLoadBalancer{
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement(){
        int current;
        int next;do {
           current = this.atomicInteger.get();
           next = current >= 2147483647 ? 0 :current+1;
           log.info("*******next值："+next);
        }while(!this.atomicInteger.compareAndSet(current,next));
        log.info("*******期望next值："+next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> instances) {
        int index = getAndIncrement() % instances.size();
        return instances.get(index);
    }
}
